import logging
import time
import redis
import pymysql
import requests
from app.commons.config import async_exec


def get_proxy(token,debug=False):
    tiquApiUrl = token
    apiRes = requests.get(tiquApiUrl, timeout=5).text
    if not debug:
        logging.warning("proxy data: %s" % (apiRes))
    print("proxy data: %s" % (apiRes))
    if apiRes=="{\"code\":10005,\"info\":\"该套餐已过期\",\"data\":[]}":
        return
    proxies = {
        'http': apiRes,
        'https': apiRes
    }
    return proxies
@async_exec
def get_current_price_by_items_once(stock_items=None, only_one=False, user_name=None,need_proxy=False,debug=False):
    # conn = pymysql.connect(
    #     host="106.55.41.183",
    #     port=3306,
    #     user="root",
    #     password="pj20211112",
    #     db="snkr",
    #     autocommit=True
    # )
    # cur=conn.cursor()
    with pymysql.connect(
        host="106.55.41.183",
        port=3306,
        user="root",
        password="pj20211112",
        db="snkr",
        autocommit=True
    ) as conn:
        with conn.cursor() as cur:
            if stock_items is None:
                stock_items = []
                sql="select item_id from buyer_stock_info where deleted=0 "
                if user_name:
                    sql+="and username='%s'"%(user_name)
                cur.execute(sql)
                r=cur.fetchall()
                for k in r:
                    stock_items.append(k[0])
            if not only_one:
                knife_list = [759509, 776261, 759326, 42682, 759460, 776671, 776583, 759383, 42349, 42891, 44002, 775988, 43052,
                              773696, 42530, 42961, 43162, 42779, 42461]
                stock_items += knife_list
            stock_items = set(stock_items)
            count = 0
            pool = redis.ConnectionPool(host="106.55.41.183", password="092394572",
                                        db=0, decode_responses=True)
            r=redis.Redis(connection_pool=pool)
            cookie = r.get("item_price_cookie")
            token = r.get("proxy_token")
            if need_proxy:
                proxies=get_proxy(token,debug)
                if not proxies:
                    if not debug:
                        logging.warning("failed using proxy, using local ip")
                    need_proxy=False
            for itemid in stock_items:
                if itemid in [33881]:
                    continue
                url = "https://buff.163.com/api/market/goods/sell_order?game=csgo&goods_id=%s&page_num=1&sort_by=default&mode=&allow_tradable_cooldown=1&_=1678171393743" % (
                    itemid)
                payload = {}
                time.sleep(1)
                headers = {
                    'authority': 'buff.163.com',
                    'accept': 'application/json, text/javascript, */*; q=0.01',
                    'accept-language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
                    'cookie': cookie.encode("utf-8").decode("latin1"),
                    'referer': 'https://buff.163.com/goods/886642?from=market',
                    'sec-ch-ua': '"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"',
                    'sec-ch-ua-mobile': '?0',
                    'sec-ch-ua-platform': '"macOS"',
                    'sec-fetch-dest': 'empty',
                    'sec-fetch-mode': 'cors',
                    'sec-fetch-site': 'same-origin',
                    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
                    'x-requested-with': 'XMLHttpRequest'
                }
                if need_proxy:
                    try:
                        response = requests.request("GET", url, headers=headers, data=payload,proxies=proxies)
                    except:
                        if not debug:
                            logging.warning("failed using proxy, getting new proxy")
                        print("failed using proxy, getting new proxy")
                        proxies = get_proxy(token,debug)
                        if not proxies:
                            need_proxy=False
                            if not debug:
                                logging.warning("failed using proxy, using local ip")
                            response = requests.request("GET", url, headers=headers, data=payload)
                        else:
                            response = requests.request("GET", url, headers=headers, data=payload, proxies=proxies)
                else:
                    response = requests.request("GET", url, headers=headers, data=payload)
                try:
                    rejson = response.json()
                    min_price = rejson["data"]["items"][0]["price"]
                    sql="update stock_info set quick_price = %s, mtime= %s where id = %s"%(min_price,int(time.time()),itemid)
                    cur.execute(sql)
                    conn.commit()
                    count += 1
                    if not debug:
                        logging.warning("%s,%s, %s/%s"%(itemid,min_price,count,len(stock_items)))
                    print("%s,%s, %s/%s"%(itemid,min_price,count,len(stock_items)))
                except:
                    continue
    r.set("last_update", str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))

if __name__ == '__main__':
    get_current_price_by_items_once(debug=True)